﻿using System.Reflection;
using System.IO;
using System.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

using Marbles.CMS.ContentTypes;
using System.Web.Security;

namespace Marbles.CMS.Core
{
    public class Controller : IHttpHandlerFactory
    {

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            if (url.ToLower() == "/favicon.ico") { return null; }

            if (File.Exists(pathTranslated))
            {
                return GetExistingPageHandler(context, pathTranslated);
            }

            return GetDynamicPageHandler(context, pathTranslated);
        }

        public static object CreateTypeInstance(string name)
        {
            Assembly assm = null;
            string[] arr = name.Split(',');
            if (arr.Length == 2)
            {
                assm = Assembly.Load(arr[1].Trim());
                object obj = assm.CreateInstance(arr[0].Trim());
                return obj;
            }

            return null;
        }

        public IHttpHandler GetDynamicPageHandler(HttpContext context, string filename)
        {
            ContentManagerBase cntlr = new ContentManagerBase();
            PageDefinition def = cntlr.GetPageDefinition(context.Request.Url);
            bool Anonymous = context.Request.LogonUserIdentity.IsAnonymous;
            
            if (!context.Request.LogonUserIdentity.IsAuthenticated) { Anonymous = true; }

            if (((def == null) || (!def.Visible)) || (!def.Anonymous && Anonymous))
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.StatusCode = 404;
                HttpContext.Current.Response.Status = "404 Not Found";
                HttpContext.Current.Response.Write("<html><head><title>Object Not Found</title></head><body><h1>HTTP/1.1 404 Object Not Found</h1></body></html>");
                HttpContext.Current.Response.End();
                //throw new HttpException(404, "File not found.");
            }

            IHttpHandler h = GetExistingPageHandler(context, context.Server.MapPath(def.Renderer.Renderer));
            //GetPageRenderer(def.Renderer.RendererType) as IPageController;
            ((IPageRenderer)h).PageDefinition = def;
            return h;
        }

        private IPageRenderer GetPageRenderer(string typename)
        {
            Type t = Type.GetType(typename);
            IPageRenderer pg = Activator.CreateInstance(t) as IPageRenderer;
            return pg;
        }

        public IHttpHandler GetExistingPageHandler(HttpContext context, string filename)
        {
            if (File.Exists(filename))
            {
                context.RewritePath(context.Request.Path, context.Request.Path, context.Request.Url.Query);
                context.Items["RawUrl"] = context.Request.RawUrl;
                IHttpHandler appHandler = PageParser.GetCompiledPageInstance(context.Request.Path, filename, context);
                context.RewritePath(context.Items["RawUrl"].ToString());
                return appHandler;
            }

            throw new HttpException(404, "File not found.");
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
        }

    }
}
